<template>
  <div class="container">
    <el-card class="center-card">
      <el-form :model="formData" :rules="rules" label-width="80px" class="login-form"      ref="formRef">
<!--        <el-text class="welcome-title" size="large">观弈零代码平台</el-text>-->
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="手机号" name="phoneTab">
            <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
            <el-input type="password" style="margin-top: 5px;" v-show="!showVerifyCode" v-model="formData.password" placeholder="请输入密码"></el-input>
            <el-input
                v-model="formData.code"
                size="large"
                auto-complete="off"
                placeholder="验证码"
                style="margin-top: 5px;"
                @keyup.enter="submitForm"
                v-show="!showVerifyCode"
            >
              <template #append>
              <img :src="codeUrl" @click="getCode" class="login-code-img"/>
              </template>
            </el-input>
            <el-input style="margin-top: 5px;" v-show="showVerifyCode" v-model="formData.verifyCode" placeholder="请输入短信验证码"> <template #append><el-button v-if="activeName === 'phoneTab'" :disabled="isCounting" @click="sendVerifyCode">{{ countdownText }}</el-button></template></el-input>
            <el-text class="switch-title" size="small" @click="switchVerifyMode">{{ verifyModeText }}</el-text>

          </el-tab-pane>
          <el-tab-pane label="邮箱" name="mailTab">
            <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
            <el-input type="password" style="margin-top: 5px;" v-show="!showVerifyCode" v-model="formData.password" placeholder="请输入密码"></el-input>
            <el-input style="margin-top: 5px;" v-show="showVerifyCode" v-model="formData.verifyCode" placeholder="请输入邮箱验证码"><template #append><el-button v-if="activeName === 'mailTab'" :disabled="isCounting" @click="sendVerifyCode">{{ countdownText }}</el-button></template></el-input>
            <el-input
                v-model="formData.code"
                size="large"
                auto-complete="off"
                placeholder="验证码"
                style="margin-top: 5px;"
                @keyup.enter="submitForm"
                v-show="!showVerifyCode"
            >
              <template #append>
                <img :src="codeUrl" @click="getCode" class="login-code-img"/>
              </template>
            </el-input>
            <el-text class="switch-title" size="small" @click="switchVerifyMode">{{ verifyModeText }}</el-text>
          </el-tab-pane>
        </el-tabs>
        <el-button :loading="loading" type="primary" @click="submitForm">登录</el-button>
        <el-button  type="primary" @click="goChangePwd">重置密码</el-button>
        <el-checkbox>我已阅读并同意服务协议和隐私政策</el-checkbox>
        <div class="register-link">
          还没有企业？<a @click="goToRegister">立即注册</a>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {ref, watchEffect, onMounted, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import { sendSmsVerifyCode, sendMailVerifyCode,smsVerifyCode,mailVerifyCode,loginMixed} from '@/api/login';
import { ElForm,  ElInput, ElCheckbox, ElButton, ElText, ElMessage } from 'element-plus';
import useUserStore from '@/store/modules/user'
import { getCodeImg } from "@/api/login";
import {setApplicaitonCode} from "@/utils/auth";
const userStore = useUserStore()
const formData = ref({
  phone: '',
  email: '',
  password: '',
  verifyCode: '',
  code:''
});
const formRef = ref<InstanceType<typeof ElForm>>();
const activeName = ref('phoneTab');
const verifyModeText = ref('切换消息码登录');
const showVerifyCode = ref(false);
const codeUrl = ref("");
// 验证码开关
const captchaEnabled = ref(true);
const rules = {
  phone: [
    {
      validator: (rule, value, callback) => {
        if (value === '') return callback();
        if (!/^1[3456789]\d{9}$/.test(value)) {
          return callback(new Error('手机号格式错误'));
        }
        callback();
      },
      trigger: ['blur', 'change']
    }
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (value === '') return callback();
        if (!/.+@.+\..+/.test(value)) {
          return callback(new Error('邮箱格式错误'));
        }
        callback();
      },
      trigger: 'blur'
    }
  ]
};

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function submitForm() {
  //debugger;
  let data = {
    mobile:'',
    mail:'',
    verifyMode:'',
    codeOrPassword:''
  }
  loading.value = true;
  if(activeName.value === 'phoneTab'){
    data.mobile = formData.value.phone
  }else{
    data.mail = formData.value.email
  }
  if(showVerifyCode.value) {
    data.verifyMode='verifyCodeMode';
    data.codeOrPassword = formData.value.verifyCode;
  }else{
    data.verifyMode='passwordMode'
    data.codeOrPassword = formData.value.password;
  }
  data.code = formData.value.code;
  data.uuid = formData.value.uuid;
  setApplicaitonCode('-')
  userStore.login(data).then(() => {
    const query = route.query;
    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
      if (cur !== "redirect") {
        acc[cur] = query[cur];
      }
      return acc;
    }, {});
    router.push({ path: redirect.value || "/", query: otherQueryParams });
  }).catch(() => {
    loading.value = false;
    // 重新获取验证码
     if (captchaEnabled.value) {
      getCode();
    }
  });
}
function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      formData.value.uuid = res.uuid;
    }
  });
}
function goToRegister(event: Event) {
  event.preventDefault();
  router.push('/tenantregister');
}

function switchVerifyMode() {
  //debugger;
  if (verifyModeText.value === '切换消息码登录') {
    verifyModeText.value = '切换密码登录';
    showVerifyCode.value = true;
  } else {
    verifyModeText.value = '切换消息码登录';
    showVerifyCode.value = false;
  }
}

const isCounting = ref(false);
const countdownText = ref('发送验证码');
let countdownTimeout: ReturnType<typeof setTimeout> | null = null;

function startCountdown() {
  let remainingTime = 60;
  isCounting.value = true;
  countdownText.value = `${remainingTime}s 后重新发送`;
  const intervalId = setInterval(() => {
    remainingTime--;
    if (remainingTime > 0) {
      countdownText.value = `${remainingTime}s 后重新发送`;
    } else {
      clearInterval(intervalId);
      isCounting.value = false;
      countdownText.value = '发送验证码';
    }
  }, 1000);
}

function sendVerifyCode() {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (activeName.value === 'phoneTab') {
        if(formData.value.phone.length==11) {
          sendSmsVerifyCode(formData.value.phone).then(() => {
            startCountdown();
          });
        }else{
          ElMessage.error('无效的手机号！');
        }
      } else {
        sendMailVerifyCode(formData.value.email).then(() => {
          startCountdown();
        });
      }
    } else {
      console.log('验证失败');
    }
  });

}

/**
 * 跳到修改密码页面
 */
function goChangePwd(){
  router.push('/changepassword');

}
onMounted(() => {
  // 初始化操作
});
getCode();
</script>

<style scoped>
.login-form {
  width: 300px;
  margin: auto;
}
.welcome-title {
  margin-top: 10px;
  font-size: 22px;
  font-weight: 600;
  line-height: 30px;
  color: #1f2329;
}
.switch-title {
  margin-top: 10px;
  font-size: 12px;
  line-height: 30px;
  color: #1764d7;
}
.login-form > * {
  margin-bottom: 10px;
}

.login-form .el-form-item__label span {
  cursor: pointer;
}

.register-link {
  text-align: center;
  margin-top: 10px;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  height: 80vh;           /* 设置容器高度为视口高度 */
}

.center-card {
  width: 500px; /* 根据需要设置卡片宽度 */
}
.login-code-img {
  width: 100%;
}
</style>
